import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/DizhiGuanli.dart';
import 'package:shop/shop/life/Index.dart';
import 'package:shop/shop/life/JifenRecords.dart';
import 'package:shop/shop/life/Login.dart';
import 'package:shop/shop/life/MyYuYue.dart';
import 'package:shop/shop/life/MyShouCang.dart';
import 'package:shop/shop/life/OrderListPage.dart';
import 'package:shop/shop/life/RefundListPage.dart';
import 'package:shop/shop/merchant/Index.dart' as MerchantIndex;
import 'package:shop/shop/rider/GaiMima.dart';
import 'package:shop/shop/rider/Index.dart' as RiderIndex;
class MyCenter extends StatefulWidget {
  MyCenter({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyCenter createState() => _MyCenter();
}
class _MyCenter extends State<MyCenter> {
  String userId="";
  String userName="请先登录";
  String jifen="0";
  bool isLogin=false;
  dynamic _iconPath;
  var tupian;
  String icon = "http://img.alicdn.com/imgextra/i4/6000000001151/O1CN01aX5NCk1KNCZJNCGLZ_!!6000000001151-0-lubanimage.jpg";//用户头像
  SharedPreferences prefs;

  //定时器
  // var time=Timer.periodic(
  //     // Duration(milliseconds: 1500),
  //   Duration(seconds:2),
  //     (time) async {
  //       var x = await HttpUtil().get("/app/user/getJifen");
  //       if(x['code']==200){
  //         String jifen = x['data'];
  //         print("积分："+jifen);
  //       }
  //       // print('currentTime='+DateTime.now().toString());//当前时间
  //       // time.cancel();// 取消定时器
  //     }
  // );

  // 构造方法
  _MyCenter() {
    _getUserInfo();
  }
  // 获取用户信息
  void _getUserInfo () async {
     // 获取内存存储的用户id
     prefs = await SharedPreferences.getInstance();
     if(prefs.getBool("isLogin")){
       userId = prefs.getString("userId");
       userName = prefs.getString("userName");
       // jifen = prefs.getString("userJifen");
       isLogin = prefs.getBool("isLogin");
       var x = await HttpUtil().get("/app/user/getJifen?userId="+userId);//跳转到当前页面就重新查积分
       if(x['code']==200){
         jifen = x['data']['userIntegral'].toString();
         icon = x['data']['icon'];
         if(icon==null || icon==""){
           icon = "http://img.alicdn.com/imgextra/i4/6000000001151/O1CN01aX5NCk1KNCZJNCGLZ_!!6000000001151-0-lubanimage.jpg";
         }else{
           icon = Config.getInstance().getHost()+"upload/userIcon/"+icon;
         }
       }
       setState(() {});
     }
  }
  Widget _showNameOrLogin()  {
    if(isLogin){
      return Text(userName);
    }else{
      return GestureDetector(child: Text("请先登录"),onTap: (){
        MyRoute.push(Login());
      },);
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("个人中心"),
      ),
      body: new SingleChildScrollView(
      physics: BouncingScrollPhysics(),
        child: Container(
          child: Column(
            children: [
              Container(
                height: 100,
                decoration: BoxDecoration(
                    color: Colors.deepOrange
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(child: Container(
                      height: 80,
                      width: 80,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius:BorderRadius.circular(40),
                        image: new DecorationImage(
                          image: new NetworkImage(icon),
                          //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                          // centerSlice: new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
                        ),
                      ),
                    ),onTap: () async {
                      // var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                      // // _iconPath=s;
                      // File file = new File(s.path);
                      // print(file);
                      // var result = await HttpUtil().upload("/upload", file);
                      // tupian = result['data'];
                      // SharedPreferences prefs = await SharedPreferences.getInstance();
                      // var userid = prefs.getString("userId");
                      //
                      // var res = await HttpUtil().get("app/user/editUserIcon?userId=${userid}&icon=${tupian}",);
                      // if(res['code']==200){
                      //   setState(()  {
                      //     icon = Config.getInstance().getHost()+"upload/userIcon/"+tupian;
                      //   });
                      // }else{
                      //   Fluttertoast.showToast(
                      //       msg: res['msg'],
                      //       toastLength: Toast.LENGTH_SHORT,
                      //       gravity: ToastGravity.BOTTOM,
                      //       timeInSecForIosWeb: 1,
                      //       backgroundColor: Colors.black45,
                      //       textColor: Colors.white,
                      //       fontSize: 16.0
                      //   );
                      // }
                    },
                    ),
                    Container(
                      child: _showNameOrLogin(),
                    ),
                    Container(
                      child: Text("积分:${jifen}"),
                    )
                  ],
                ),
              ),
              // 我的订单
              Container(
                padding: EdgeInsets.fromLTRB(10, 10, 10, 20),
                margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                decoration: BoxDecoration(
                    color: Colors.white
                ),
                child: Column(
                  children: [
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            child: Text("我的订单"),
                          ),
                          GestureDetector(
                            child: Row(
                              children: [
                                Text("全部订单"),
                                Icon(CupertinoIcons.chevron_right)
                              ],
                            ),
                            onTap: (){
                              MyRoute.push(OrderListPage(showIndex:"0"));
                            },
                          )
                        ],
                      ),
                    ),
                    Divider(),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        GestureDetector(child:
                        Column(
                          children: [
                            Icon(Icons.local_atm),
                            Text("待付款")
                          ],
                        ),
                            onTap: (){
                              MyRoute.push(OrderListPage(showIndex:'1'));
                            }
                        ),
                        // GestureDetector(child:
                        // Column(
                        //   children: [
                        //     Icon(Icons.query_builder),
                        //     Text("待发货")
                        //   ],
                        // ),
                        //     onTap: (){
                        //       MyRoute.push(OrderListPage(showIndex:'2'));
                        //     }
                        // ),
                        GestureDetector(child:  Column(
                          children: [
                            Icon(Icons.local_shipping_outlined),
                            Text("待收货")
                          ],
                        ),
                            onTap: (){
                              MyRoute.push(OrderListPage(showIndex:'2'));
                            }
                        ),
                        GestureDetector(child:  Column(
                          children: [
                            Icon(Icons.where_to_vote_outlined),
                            Text("已签收")
                          ],
                        ),
                            onTap: (){
                              MyRoute.push(OrderListPage(showIndex:'3'));
                            }
                        ),
                        // GestureDetector(child:  Column(
                        //   children: [
                        //     Icon(Icons.sync),
                        //     Text("退换货")
                        //   ],
                        // ),
                        //     onTap: (){
                        //       MyRoute.push(RefundListPage());
                        //     }
                        // )

                      ],
                    )
                  ],
                ),
              ),
              // 收获地址
              GestureDetector(child:
              Container(
                padding: EdgeInsets.fromLTRB(10, 10, 10, 20),
                margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                decoration: BoxDecoration(
                    color: Colors.white
                ),
                child: Column(
                  children: [
                    GestureDetector(child:Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Row(
                            children: [
                              Icon(CupertinoIcons.location_circle),
                              Container(
                                child: Text("收货地址"),
                              )
                            ],
                          ),

                        ),
                        Icon(CupertinoIcons.chevron_right)
                      ],
                    ) ,
                      onTap: (){
                        MyRoute.push(DizhiGuanli());
                      },
                      behavior: HitTestBehavior.opaque,
                    )
                    ,
                    Divider(),
                    // 修改密码
                    // GestureDetector(child: Row(
                    //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //   children: [
                    //     Container(
                    //       child: Row(
                    //         children: [
                    //           Icon(CupertinoIcons.gear_alt),
                    //           Container(
                    //             child: Text("修改密码"),
                    //           )
                    //         ],
                    //       ),
                    //
                    //     ),
                    //     Icon(CupertinoIcons.chevron_right)
                    //   ],
                    // ),
                    //   onTap: (){
                    //     MyRoute.push(GaiMima());
                    //   },
                    //   behavior: HitTestBehavior.opaque,// 点击空白
                    // )
                    // ,
                    // Divider(),
                    // 积分记录
                    GestureDetector(child:Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Row(
                            children: [
                              Icon(CupertinoIcons.list_bullet),
                              Container(
                                child: Text("消费记录"),
                              )
                            ],
                          ),

                        ),
                        Icon(CupertinoIcons.chevron_right)
                      ],
                    ) ,
                      onTap: (){
                        // 跳转到积分页面
                        MyRoute.push(JifenRecords());
                      },
                      behavior: HitTestBehavior.opaque,
                    )
                    ,
                    Divider(),
                    // 编辑信息
                    GestureDetector(child:Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Row(
                            children: [
                              Icon(CupertinoIcons.alarm),
                              Container(
                                child: Text("我的预约"),
                              )
                            ],
                          ),

                        ),
                        Icon(CupertinoIcons.chevron_right)
                      ],
                    ) ,
                      onTap: (){
                       MyRoute.push(MyYuYue());
                      },
                      behavior: HitTestBehavior.opaque,
                    ),
                    Divider(),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            child: Row(
                              children: [
                                Icon(Icons.star_border),
                                Container(
                                  child: Text("我的收藏"),
                                )
                              ],
                            ),
                          ),
                          Icon(CupertinoIcons.chevron_right)
                        ],
                      ) ,
                      onTap: () async {
                        MyRoute.push(MyShouCang());
                      },
                    ),
                    Divider(),
                    // 退出登录
                    // GestureDetector(child:Row(
                    //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //   children: [
                    //     Container(
                    //       child: Row(
                    //         children: [
                    //           Icon(CupertinoIcons.arrow_right_square),
                    //           Container(
                    //             child: Text("退出登录"),
                    //           )
                    //         ],
                    //       ),
                    //     ),
                    //     Icon(CupertinoIcons.chevron_right)
                    //   ],
                    // ) ,
                    //   onTap: (){
                    //     if(userId!=null && userId!=""){
                    //       showDialog<Null>(
                    //         context: context,
                    //         barrierDismissible: false,
                    //         builder: (BuildContext context) {
                    //           return new AlertDialog(
                    //             title: new Text('退出登录'),
                    //             content: Text('确认退出?'),
                    //             actions: <Widget>[
                    //               new FlatButton(
                    //                 child: new Text('取消'),
                    //                 onPressed: (){
                    //                   Navigator.of(context).pop();
                    //                 },
                    //               ),
                    //               new FlatButton(
                    //                 child: new Text('确定'),
                    //                 onPressed: () async{
                    //                   print("点击了退出");
                    //                   prefs.remove("userId");
                    //                   prefs.remove("userName");
                    //                   prefs.remove("userJifen");
                    //                   prefs.setBool("isLogin", false);
                    //                   MyRoute.push(Index());
                    //                   setState(() {});
                    //                 },
                    //               ),
                    //             ],
                    //           );
                    //         },
                    //       ).then((val) {
                    //         // print(val);
                    //       });
                    //     }
                    //   },
                    //   behavior: HitTestBehavior.opaque,
                    // ),
                    // Divider(),
                    // 商家入口
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child:Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          child: Row(
                            children: [
                              Icon(Icons.business),
                              Container(
                                child: Text("我是商家"),
                              )
                            ],
                          ),
                        ),
                        Icon(CupertinoIcons.chevron_right)
                      ],
                    ) ,
                      onTap: () async {
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        String userId = prefs.getString("userId");
                        var x = await HttpUtil().get("/waimai/merchant/verifyMerchantandRider?userId="+userId+"&type=1");
                        if(x['code']==200){
                          prefs.setString("merchantID", x['data']['id']);//商家ID
                          prefs.setString("merchantType", x['data']['mtype']);//商家类型
                          prefs.setString("merchantName", x['data']['mname']);//商家名称
                          prefs.setString("merchantJifen", x['data']['jifen'].toString());//积分
                          prefs.setString("mType",x['count'].toString());//商户类型（0：外卖型商户  1：服务型商户）
                          MyRoute.push(MerchantIndex.Index(showIndex: "0",mType: x['count'].toString(),));
                        }else{
                          Fluttertoast.showToast(
                              msg: "您还不是商家",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        }
                      },
                    ),
                    Divider(),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            child: Row(
                              children: [
                                Icon(Icons.directions_bike),
                                Container(
                                  child: Text("我是骑手"),
                                )
                              ],
                            ),
                          ),
                          Icon(CupertinoIcons.chevron_right)
                        ],
                      ) ,
                      onTap: () async {
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        prefs.remove("isLogin");
                        String userId = prefs.getString("userId");
                        var x = await HttpUtil().get("/waimai/merchant/verifyMerchantandRider?userId="+userId+"&type=2");
                        if(x['code']==200){
                          prefs.setString("riderId", x['data']['id']);//骑手ID
                          prefs.setString("riderName", x['data']['qsName']);//骑手名称
                          prefs.setString("riderJifen", x['data']['jifen'].toString());//积分
                          // prefs.setString("riderIcon",x['data']['shouchiZhengmian']);//骑手手持证件正面照
                          // prefs.setInt("peisongStatus", x['data']['peisongStatus']);//骑手配送状态
                          MyRoute.push(RiderIndex.Index());
                        }else{
                          Fluttertoast.showToast(
                            msg: "您还不是骑手",
                            toastLength: Toast.LENGTH_SHORT,
                            gravity: ToastGravity.BOTTOM,
                            timeInSecForIosWeb: 1,
                            backgroundColor: Colors.black45,
                            textColor: Colors.white,
                            fontSize: 16.0
                          );
                        }
                      },
                    ),
                    // Divider(),
                    // GestureDetector(
                    //   behavior: HitTestBehavior.opaque,
                    //   child:Row(
                    //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //     children: [
                    //       Container(
                    //         child: Row(
                    //           children: [
                    //             Icon(Icons.directions_bike),
                    //             Container(
                    //               child: Text("定位测试"),
                    //             )
                    //           ],
                    //         ),
                    //       ),
                    //       Icon(CupertinoIcons.chevron_right)
                    //     ],
                    //   ) ,
                    //   onTap: () async {
                    //     MyRoute.push(GaiMima());
                    //   },
                    // ),
                  ],
                ),
              ),),
            ],
          ),
        ),
      ),

    );
  }
}